import tkinter as tk
from tkinter import messagebox, simpledialog, filedialog, Listbox
import os

# 默认文件存储路径，在Kali Linux下使用Linux风格的路径
FILE_PATH = os.path.expanduser('~/users.txt')
# 预设文件存储路径
PRESETS_FILE = os.path.expanduser('~/presets.txt')

TEMPLATES = {
    "基本信息": ["用户名", "邮箱", "密码"],
    "自定义": []
}


def save_presets(presets):
    with open(PRESETS_FILE, 'w', encoding='utf-8') as file:
        for name, fields in presets.items():
            fields_str = ','.join(fields)
            file.write(f"{name}:{fields_str}\n")


def load_presets():
    if os.path.exists(PRESETS_FILE):
        presets = {}
        with open(PRESETS_FILE, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            for line in lines:
                name, fields_str = line.strip().split(':')
                fields = fields_str.split(',')
                presets[name] = fields
        return presets
    return TEMPLATES.copy()


class App:
    def __init__(self, root):
        self.root = root
        # 调大主窗口大小
        self.root.geometry("800x600")
        self.root.title("数据库 GUI 示例")
        self.current_page = None
        self.template = None
        self.fields = []
        self.entries = []
        self.presets = load_presets()

        # 主菜单页面
        self.main_menu()

    def main_menu(self):
        if self.current_page:
            self.current_page.destroy()
        self.current_page = tk.Frame(self.root, bg="#f0f0f0")
        self.current_page.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

        title_label = tk.Label(self.current_page, text="请选择模板:", font=("Arial", 16), bg="#f0f0f0")
        title_label.pack(pady=10)

        # 使用列表框展示预设
        self.preset_listbox = Listbox(self.current_page, font=("Arial", 12))
        self.preset_listbox.pack(pady=10)
        for preset_name in self.presets:
            self.preset_listbox.insert(tk.END, preset_name)

        select_button = tk.Button(self.current_page, text="选择模板", font=("Arial", 12),
                                  command=self.select_selected_template)
        select_button.pack(pady=5)

        # 添加新建预设按钮
        new_preset_button = tk.Button(self.current_page, text="新建预设", font=("Arial", 12),
                                      command=self.create_new_preset)
        new_preset_button.pack(pady=20)

        # 添加删除预设按钮
        delete_preset_button = tk.Button(self.current_page, text="删除预设", font=("Arial", 12),
                                         command=self.delete_selected_preset)
        delete_preset_button.pack(pady=20)

        # 添加更改文件存储位置的按钮
        change_path_button = tk.Button(self.current_page, text="更改文件存储位置", font=("Arial", 12),
                                       command=self.change_file_path)
        change_path_button.pack(pady=20)

    def create_new_preset(self):
        preset_name = simpledialog.askstring("新建预设", "请输入预设名称:")
        if preset_name:
            fields_str = simpledialog.askstring("新建预设", "请输入字段，用逗号分隔:")
            if fields_str:
                self.presets[preset_name] = fields_str.split(',')
                save_presets(self.presets)
                self.preset_listbox.insert(tk.END, preset_name)
                messagebox.showinfo("成功", "预设创建成功！")
            else:
                messagebox.showerror("错误", "未输入有效字段！")
        else:
            messagebox.showerror("错误", "未输入预设名称！")

    def select_selected_template(self):
        selected_index = self.preset_listbox.curselection()
        if selected_index:
            template_name = self.preset_listbox.get(selected_index)
            if template_name == "自定义":
                fields_str = simpledialog.askstring("自定义模板", "请输入自定义字段，用逗号分隔:")
                if fields_str:
                    self.fields = fields_str.split(',')
                else:
                    messagebox.showerror("错误", "未输入有效字段！")
                    return
            else:
                self.fields = self.presets[template_name]

            self.template = template_name
            self.show_input_page()
        else:
            messagebox.showerror("错误", "请选择一个模板！")

    def show_input_page(self):
        if self.current_page:
            self.current_page.destroy()
        self.current_page = tk.Frame(self.root, bg="#f0f0f0")
        self.current_page.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

        # 创建画布和滚动条
        canvas = tk.Canvas(self.current_page, bg="#f0f0f0")
        scrollbar = tk.Scrollbar(self.current_page, orient="vertical", command=canvas.yview)
        scrollable_frame = tk.Frame(canvas, bg="#f0f0f0")

        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(
                scrollregion=canvas.bbox("all")
            )
        )

        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        self.entries = []
        for i, field in enumerate(self.fields):
            label = tk.Label(scrollable_frame, text=field + ":", font=("Arial", 12), bg="#f0f0f0")
            label.pack(pady=5)
            entry = tk.Entry(scrollable_frame, font=("Arial", 12))
            entry.pack(pady=5)
            self.entries.append(entry)

        add_button = tk.Button(scrollable_frame, text="添加信息", font=("Arial", 12), command=self.add_info)
        add_button.pack(pady=10)

        search_button = tk.Button(scrollable_frame, text="查询信息", font=("Arial", 12), command=self.search_info)
        search_button.pack(pady=10)

        update_button = tk.Button(scrollable_frame, text="更新信息", font=("Arial", 12), command=self.update_info)
        update_button.pack(pady=10)

        delete_button = tk.Button(scrollable_frame, text="删除信息", font=("Arial", 12), command=self.delete_info)
        delete_button.pack(pady=10)

        back_button = tk.Button(scrollable_frame, text="返回主菜单", font=("Arial", 12), command=self.main_menu)
        back_button.pack(pady=10)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

    def add_info(self):
        values = [entry.get() for entry in self.entries]
        if all(values):
            with open(FILE_PATH, 'a', encoding='utf-8') as file:
                file.write(','.join(values) + '\n')
            messagebox.showinfo("成功", "信息添加成功！")
            for entry in self.entries:
                entry.delete(0, tk.END)
        else:
            messagebox.showerror("错误", "请填写所有字段！")

    def search_info(self):
        if os.path.exists(FILE_PATH):
            with open(FILE_PATH, 'r', encoding='utf-8') as file:
                lines = file.readlines()
            info_window = tk.Toplevel(self.root)
            info_window.title("信息查询结果")
            # 调大查询结果显示窗口大小
            info_window.geometry("1000x800")
            text = tk.Text(info_window, font=("Arial", 12))
            text.pack(pady=10, padx=10, fill="both", expand=True)
            for i, line in enumerate(lines, start=1):
                values = line.strip().split(',')
                info_str = f"ID: {i}"
                for field, value in zip(self.fields, values):
                    info_str += f", {field}: {value}"
                text.insert(tk.END, info_str + '\n')
        else:
            messagebox.showinfo("提示", "还没有信息记录。")

    def update_info(self):
        # 这里为了简单，我们可以复用查询的逻辑来选择要更新的记录
        self.search_info()
        record_id = simpledialog.askinteger("更新信息", "请输入要更新的记录ID:")
        if record_id:
            values = [entry.get() for entry in self.entries]
            if all(values):
                if os.path.exists(FILE_PATH):
                    with open(FILE_PATH, 'r', encoding='utf-8') as file:
                        lines = file.readlines()
                    if 1 <= record_id <= len(lines):
                        lines[record_id - 1] = ','.join(values) + '\n'
                        with open(FILE_PATH, 'w', encoding='utf-8') as file:
                            file.writelines(lines)
                        messagebox.showinfo("成功", "信息更新成功！")
                        for entry in self.entries:
                            entry.delete(0, tk.END)
                    else:
                        messagebox.showerror("错误", "输入的记录ID不存在！")
                else:
                    messagebox.showinfo("提示", "还没有信息记录。")
            else:
                messagebox.showerror("错误", "请填写所有字段！")

    def delete_info(self):
        if os.path.exists(FILE_PATH):
            with open(FILE_PATH, 'r', encoding='utf-8') as file:
                lines = file.readlines()
            delete_window = tk.Toplevel(self.root)
            delete_window.title("选择要删除的记录")
            # 调大删除选择窗口大小
            delete_window.geometry("1000x800")
            listbox = Listbox(delete_window, font=("Arial", 12))
            listbox.pack(pady=10, padx=10, fill="both", expand=True)
            for i, line in enumerate(lines, start=1):
                values = line.strip().split(',')
                info_str = f"ID: {i}"
                for field, value in zip(self.fields, values):
                    info_str += f", {field}: {value}"
                listbox.insert(tk.END, info_str)

            def confirm_delete():
                selected_index = listbox.curselection()
                if selected_index:
                    record_id = selected_index[0] + 1
                    del lines[record_id - 1]
                    with open(FILE_PATH, 'w', encoding='utf-8') as file:
                        file.writelines(lines)
                    messagebox.showinfo("成功", "信息删除成功！")
                    delete_window.destroy()
                else:
                    messagebox.showerror("错误", "请选择要删除的记录！")

            confirm_button = tk.Button(delete_window, text="确认删除", font=("Arial", 12), command=confirm_delete)
            confirm_button.pack(pady=10)
        else:
            messagebox.showinfo("提示", "还没有信息记录。")

    def change_file_path(self):
        global FILE_PATH
        new_path = filedialog.asksaveasfilename(defaultextension=".txt",
                                                filetypes=[("文本文件", "*.txt")],
                                                initialfile=os.path.basename(FILE_PATH))
        if new_path:
            FILE_PATH = new_path
            messagebox.showinfo("成功", f"文件存储位置已更改为 {FILE_PATH}")

    def delete_selected_preset(self):
        selected_index = self.preset_listbox.curselection()
        if selected_index:
            preset_name = self.preset_listbox.get(selected_index)
            if preset_name in ["基本信息", "自定义"]:
                messagebox.showerror("错误", "默认预设不能删除！")
                return
            del self.presets[preset_name]
            save_presets(self.presets)
            self.preset_listbox.delete(selected_index)
            messagebox.showinfo("成功", "预设删除成功！")
        else:
            messagebox.showerror("错误", "请选择要删除的预设！")


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
